﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model.WaiGaoQiao;
using WaiGaoQiaoWeb.Models;
using WaiGaoQiaoWeb.JsonEntities;
using System.Data;
using AutoMapper;
using System.IO;

namespace WaiGaoQiaoWeb.Controllers
{
    public class MenuConfigurationController : Controller
    {
        private MenuConfigurationInfo meninfo = new MenuConfigurationInfo(true);

        public ActionResult MenuConfigurationIndex()
        {
            ViewData["MenuType"] = GetMenuType();
            ViewData["NodeID"] = SelNodeID(-1, "请选择...");
            ViewData["PeriodCode"] = SelPeriodCode(-1, "请选择...");
            return View();
        }

        /// <summary>
        /// 获取菜单类型列表
        /// </summary>
        /// <returns></returns>
        public IList<SelectListItem> GetMenuType()
        {
            IDictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(-1, "请选择...");
            dic.Add(1, "大荤");
            dic.Add(2, "小荤");
            dic.Add(3, "素菜");
            dic.Add(4, "汤饭点心类");
            IList<SelectListItem> selectList =
                dic.Select(m => new SelectListItem() { Text = m.Value.ToString(), Value = m.Key.ToString() }).ToList();
            return selectList;
        }

        /// <summary>
        /// 获取菜单配置列表
        /// </summary>
        /// <param name="pvm"></param>
        /// <returns></returns>
        public ActionResult GetList(PageVM pvm)
        {
            string query = " where 1=1 ";
            if (string.IsNullOrEmpty(pvm.query))
            {
                query += " and 1=1";
            }
            else
            {
                string[] param = pvm.query.Split(',');
                if (param[0].ToString() != "")
                {
                    query += " and MenuConDate>='" + param[0] + "'";
                }
                if (param[1].ToString() != "")
                {
                    query += " and MenuConDate<='" + param[1] + "'";
                }
                if (param[2].ToString() != "-1")
                {
                    query += " and MenuType='" + param[2] + "'";
                }
                if (param[3].ToString() != "")
                {
                    query += " and MenuName like '%" + param[3] + "%'";
                }
                if (param[4].ToString() != "-1")
                {
                    query += " and NodeID='" + param[4] + "'";
                }
                if (param[5].ToString() != "-1")
                {
                    query += " and PeriodCode='" + param[5] + "'";
                }
            }
            IList<MenuConfigurationInfo> menlist = meninfo.SelMenuConInfo(pvm.rp, pvm.page, query);
            JsonFlexiGridData jfgd = new JsonFlexiGridData();
            jfgd.page = pvm.page;
            jfgd.total = meninfo.GetMenuConcount(query);
            List<string> v;
            foreach (MenuConfigurationInfo item in menlist)
            {
                #region
                v = new List<string>();
                v.Add(item.MenuConId.ToString());
                v.Add(item.MenuConDate.ToString("yyyy-MM-dd"));
                v.Add(item.MenuTypeName);
                v.Add(item.MenuName);
                v.Add(item.MenuPrice.ToString());
                v.Add(item.Nodename.ToString());
                v.Add(item.PeriodName.ToString());
                #endregion
                FlexiGridRow fgr = new FlexiGridRow()
                {
                    id = item.MenuConId.ToString(),
                    cell = v
                };
                jfgd.rows.Add(fgr);
            }
            return Json(jfgd);
        }

        public ActionResult AddMenuCon()
        {
            ViewData["MenuType"] = GetMenuType();
            ViewData["Menuleft"] = SelLeftBox("");
            ViewData["Menuright"] = SelRightBox();
            ViewData["NodeID"] = SelNodeID(0, "");
            ViewData["PeriodCode"] = SelPeriodCode(0, "");
            return View();
        }

        public ActionResult EditMenuCon(string Date, string ID)
        {
            ViewData["MenuType"] = GetMenuType();
            ViewData["Menuleft"] = SelLeftBox("");
            ViewData["Menuright"] = SelRightBoxEdit(Date, ID);
            ViewData["NodeID"] = SelNodeID(0, "");
            ViewData["PeriodCode"] = SelPeriodCode(0, "");
            DataSet ds = meninfo.SelEdit(Date, ID);
            MenuConfigurationVM vm = new MenuConfigurationVM();
            vm.Nodename = ds.Tables[0].Rows[0]["Nodename"].ToString();
            vm.PeriodName = ds.Tables[0].Rows[0]["PeriodName"].ToString();
            vm.NodeID = Convert.ToInt32(ds.Tables[0].Rows[0]["NodeID"].ToString());
            vm.PeriodCode = Convert.ToInt32(ds.Tables[0].Rows[0]["PeriodCode"].ToString());
            vm.MenuConDateToString = Convert.ToDateTime(ds.Tables[0].Rows[0]["MenuConDate"]).ToString("yyyy-MM-dd");
            vm.MenuConDate = Convert.ToDateTime(ds.Tables[0].Rows[0]["MenuConDate"]);
            return View(vm);
        }

        public IList<SelectListItem> SelNodeID(int i, string str)
        {
            IList<MenuConfigurationInfo> menlist = meninfo.SelNodeID();
            IDictionary<int, string> dic = new Dictionary<int, string>();
            if (i == -1)
            {
                dic.Add(i, str);
            }
            foreach (MenuConfigurationInfo item in menlist)
            {
                dic.Add(Convert.ToInt32(item.NodeID), item.Nodename);
            }
            IList<SelectListItem> selectList =
                dic.Select(m => new SelectListItem() { Text = m.Value.ToString(), Value = m.Key.ToString() }).ToList();
            return selectList;
        }

        public IList<SelectListItem> SelPeriodCode(int i, string str)
        {
            IList<MenuConfigurationInfo> menlist = meninfo.SelPeriodCode();
            IDictionary<int, string> dic = new Dictionary<int, string>();
            if (i == -1)
            {
                dic.Add(i, str);
            }
            foreach (MenuConfigurationInfo item in menlist)
            {
                dic.Add(Convert.ToInt32(item.PeriodCode), item.PeriodName);
            }
            IList<SelectListItem> selectList =
                dic.Select(m => new SelectListItem() { Text = m.Value.ToString(), Value = m.Key.ToString() }).ToList();
            return selectList;
        }

        public IList<SelectListItem> SelRightBoxEdit(string Date, string ID)
        {
            IList<MenuConfigurationInfo> menlist = meninfo.SelRightBoxEdit(Date, ID);
            IDictionary<int, string> dic = new Dictionary<int, string>();
            foreach (MenuConfigurationInfo item in menlist)
            {
                dic.Add(Convert.ToInt32(item.MenuId), item.MenuName);
            }
            IList<SelectListItem> selectList =
                dic.Select(m => new SelectListItem() { Text = m.Value.ToString(), Value = m.Key.ToString() }).ToList();
            return selectList;
        }

        public IList<SelectListItem> SelRightBox()
        {
            IDictionary<int, string> dic = new Dictionary<int, string>();
            IList<SelectListItem> selectList =
                dic.Select(m => new SelectListItem() { Text = m.Value.ToString(), Value = m.Key.ToString() }).ToList();
            return selectList;
        }

        public ActionResult GetLeftBox(string Select)
        {
            ViewData["Menuleft"] = SelLeftBox(Select);
            return Json(ViewData["Menuleft"]);
        }

        /// <summary>
        /// 获取下拉列表
        /// </summary>
        /// <returns></returns>
        public IList<SelectListItem> SelLeftBox(string Select)
        {
            string query = " and 1=1 ";
            if (string.IsNullOrEmpty(Select))
            {
                query += " and 1=1";
            }
            else
            {
                string[] param = Select.Split(',');
                if (param[0].ToString() != "-1")
                {
                    query += " and MenuType='" + param[0] + "'";
                }
                if (param[1].ToString() != "")
                {
                    query += " and MenuName like '%" + param[1] + "%'";
                }
            }
            IList<MenuConfigurationInfo> menlist = meninfo.SelLeftBox(query);
            IDictionary<int, string> dic = new Dictionary<int, string>();
            foreach (MenuConfigurationInfo item in menlist)
            {
                dic.Add(Convert.ToInt32(item.MenuId), item.MenuName);
            }
            IList<SelectListItem> selectList =
                dic.Select(m => new SelectListItem() { Text = m.Value.ToString(), Value = m.Key.ToString() }).ToList();
            return selectList;
        }

        /// <summary>
        /// 保存(添加菜单配置)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SaveMenuConAdd(MenuConfigurationVM model)
        {
            string menall = model.MenuAll.Remove(model.MenuAll.Length - 1);
            string[] smenall = menall.Split(',');
            int result = 0;
            if (ModelState.IsValid)
            {
                MenuConfigurationInfo men = new MenuConfigurationInfo()
                {
                    MenuConDate = model.MenuConDate,
                    NodeID = model.NodeID,
                    PeriodCode = model.PeriodCode,
                    Operator = ((LogOnModel)(System.Web.HttpContext.Current.Session["user"])).LogName
                };
                result = meninfo.SaveMenuConAdd(men, smenall);
            }
            return Json(result);
        }

        /// <summary>
        /// 保存(修改菜单配置)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SaveMenuConEdit(MenuConfigurationVM model)
        {
            string menall = model.MenuAll.Remove(model.MenuAll.Length - 1);
            string[] smenall = menall.Split(',');
            int result = 0;
            if (ModelState.IsValid)
            {
                MenuConfigurationInfo men = new MenuConfigurationInfo()
                {
                    MenuConDate = model.MenuConDate,
                    NodeID = model.NodeID,
                    PeriodCode = model.PeriodCode,
                    Operator = ((LogOnModel)(System.Web.HttpContext.Current.Session["user"])).LogName
                };
                result = meninfo.SaveMenuConEdit(men, smenall);
            }
            return Json(result);
        }

        /// <summary>
        /// 删除菜单配置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DeleteMenuCon(string id)
        {
            int result = 0;
            result = meninfo.DeleteMenuCon(id);
            return Json(result);
        }

        public ActionResult FileUp1(string filename)
        {
            //string strfilename = Server.MapPath(filename);
            //string strfilename = filename;
            //string Operator = ((LogOnModel)(System.Web.HttpContext.Current.Session["user"])).LogName;
            //HttpPostedFileBase file = Request.Files["file1"];
            //string i = meninfo.ExcelDataSource(strfilename, "导入模板", Operator);
            //return Json(i);
            string strToFilePath = "/";
            string strToFileFullPath = HttpContext.Server.MapPath(strToFilePath);
            // 文件名
            string fileNamea = "F21A.xls";

            // 将要保存的完整文件名
            string strToFile = strToFileFullPath + fileNamea;
            string strfilename = strToFile;
            string Operator = ((LogOnModel)(System.Web.HttpContext.Current.Session["user"])).LogName;
            HttpPostedFileBase file = Request.Files["file1"];
            string i = meninfo.ExcelDataSource(strfilename, "导入模板", Operator);
            return Json(i);
            //string j1 = "showLoadingMsg(\"导入成功!\", { left: 400, top: 6 }, true, 3000);";
        }

        /// <summary>
        /// 匯入方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public ActionResult Import(FormCollection collection, HttpPostedFileBase importFile)
        {
            string path = collection["h_filePath"]; // 對應的xml

            // 检查保存的路径 是否有/结尾
            string strToFilePath = "/";

            // 物理完整路径
            string strToFileFullPath = HttpContext.Server.MapPath(strToFilePath);

            // 检查是否有该路径  没有就创建
            if (!Directory.Exists(strToFileFullPath))
            {
                Directory.CreateDirectory(strToFileFullPath);
            }

            // 文件名
            string fileNamea = "F21A.xls";

            // 将要保存的完整文件名
            string strToFile = strToFileFullPath + fileNamea;

            // 另存文件
            importFile.SaveAs(strToFile);

            //FileInfo newFile = new FileInfo(strToFile);
            //if (System.IO.File.Exists(newFile.FullName))
            //{
            //    // 刪除暫存的文件
            //    System.IO.File.Delete(newFile.FullName);
            //}zzz
            //string strfilename = strToFile;
            //string Operator = ((LogOnModel)(System.Web.HttpContext.Current.Session["user"])).LogName;
            //HttpPostedFileBase file = Request.Files["file1"];
            //string i = meninfo.ExcelDataSource(strfilename, "导入模板", Operator);
            //string j1 = "showLoadingMsg(\"导入成功!\", { left: 400, top: 6 }, true, 3000);";
            return Json(1);
            //return View();

        }
    }
}
